Examples of plotly

library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.1     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.2     ✔ tibble    3.3.0
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.1.0     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(p8105.datasets)
library(plotly)
## 
## Attaching package: 'plotly'
## 
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## 
## The following object is masked from 'package:stats':
## 
##     filter
## 
## The following object is masked from 'package:graphics':
## 
##     layout
library(flexdashboard)
data("instacart")

Clean the dataset

instacart_clean = 
  instacart |> 
  select(
    user_id,
    product_name,
    department,
    aisle,
    add_to_cart_order,
    reordered,
    order_hour_of_day,
    order_dow
  ) |> drop_na()

Orders by Department (bar plot)

dept_counts = instacart_clean |>
count(department) |>
arrange(desc(n))

plot_ly(
  data = dept_counts,
  x = ~reorder(department, n),
  y = ~n,
  type = "bar",
  color = ~department,
  colors = "viridis") |>
  layout(
  title = "Number of Orders by Department",
  xaxis = list(title = "Department"),
  yaxis = list(title = "Number of Orders"))

Distribution of Add-to-Cart Order by Department (box plot)

plot_ly(
  data = instacart_clean,
  x = ~department,
  y = ~add_to_cart_order,
  color = ~department,
  type = "box",
  colors = "viridis") |>
  layout(
  title = "Add-to-Cart Order by Department",
  xaxis = list(title = "Department"),
  yaxis = list(title = "Add-to-Cart Position"))

Orders by Hour of Day (Scatter Plot)

hourly = instacart_clean|>
  group_by(order_hour_of_day, department) |>
  summarize(order_count = n(), .groups = "drop")

plot_ly(
  data = hourly,
  x = ~order_hour_of_day,
  y = ~order_count,
  color = ~department,
  type = "scatter",
  mode = "markers",
  colors = "viridis") |>
  layout(
  title = "Orders Throughout the Day by Department",
  xaxis = list(title = "Hour of Day"),
  yaxis = list(title = "Number of Orders"))